﻿using MediatR;
using MES.Bom.API.Application.Command.成品命令;
using MES.Bom.Domain;
using MES.Bom.ErrorCode;
using MES.Bom.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Bom.API.Application.CommandHandler.成品命令处理
{
    /// <summary>
    /// 获取成品列表命令处理器
    /// </summary>
    public class GoodsQueryCommandHandler : IRequestHandler<GoodsQueryCommand, APIResult<APIPaging<Goods>>>
    {
        private readonly IBaseRepository<Goods> goodsRepository;
        private readonly ILogger<GoodsQueryCommandHandler> logger;
        public GoodsQueryCommandHandler(IBaseRepository<Goods> goodsRepository, ILogger<GoodsQueryCommandHandler> logger = null)
        {
            this.goodsRepository = goodsRepository;
            this.logger = logger;
        }

        public  Task<APIResult<APIPaging<Goods>>> Handle(GoodsQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaging<Goods>> result = new APIResult<APIPaging<Goods>>();
                var list = goodsRepository.GetValues().AsNoTracking();
                //一个输入框支持编号和名称查询
                if (!string.IsNullOrEmpty(request.NameAndCode)) 
                {
                    list = list.Where(x => x.GoodsCode==request.NameAndCode || x.GoodsName.Contains(request.NameAndCode));
                }
                if (request.GoodsType != 0) 
                {
                    list = list.Where(x => x.GoodsType == request.GoodsType);
                }

                result.Code = APIEnums.Success;
                result.Message = "获取成品列表成功";
                logger.LogInformation("获取成品列表成功");
                list = list.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                APIPaging<Goods> paging=new APIPaging<Goods>();
                paging.TotalCount=list.Count();
                paging.TotalPages = (int)Math.Ceiling(paging.TotalPages * 1.0 / request.PageSize);
                paging.List = list.ToList();
                result.Data = paging;
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
